package models;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class GameServer {
	ServerSocket server = null;
	Socket client = null;

	List<String> lista;
	List<ClientWorker> clientworkers;
	private Game game;
	private int playersInGame;

	GameServer(int port, int startingPlayers, int startBankroll, int smallBlind) {
		/*clientworkers = new ArrayList<ClientWorker>();
		try {
			server = new ServerSocket(port);
			System.out.println("Server on port " + server.getLocalPort() + " started.");
		} catch (IOException e) {
			System.out.println("Could not listen on port " + port + ".");
			System.exit(1);
		}
		game = new Game(startingPlayers, this, clientworkers, startBankroll, smallBlind);*/
	}

	public void listenSocket() {
		while (true) {
			ClientWorker cw;
			try {
				client = server.accept();
				System.out.println("Client " + client.getInetAddress() + " connected on port " + client.getPort());
			} catch (IOException e) {
				System.out.println("Accept failed:" + client.getInetAddress());
				System.exit(1);
			}
			cw = new ClientWorker(game, playersInGame);
			playersInGame++;
			cw.start();
			clientworkers.add(cw);
			if (allPlayersConnected()) {
				game.broadcastStartInfo();
				game.initGame();
			}
		}
	}

	public boolean allPlayersConnected() {
		if (clientworkers.size() == game.numberOfPlayers) {
			return true;
		} else {
			return false;
		}
	}

	@Override
	public void finalize() {
		try {
			server.close();
		} catch (IOException e) {
			System.out.println("Could not close.");
			System.exit(-1);
		}
	}

	public static void main(String[] args) {
		/*int port = Integer.parseInt(args[0]);
		int numberOfPlayers = Integer.parseInt(args[1]);
		int startBankroll = Integer.parseInt(args[2]);
		int smallBlind = Integer.parseInt(args[3]);
		GameServer server = new GameServer(port, numberOfPlayers, startBankroll, smallBlind);
		server.listenSocket();*/
	}
}
